package com.xyhuo.leetcode.december;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 全排列Ⅱ
 * https://leetcode.cn/problems/permutations-ii/
 *
 * @time 2023/12/15
 */
public class PermuteUnique {

//    public static void main(String[] args) {
//        PermuteUnique pu = new PermuteUnique();
//        int[] nums = {1, 1, 1, 2};
//        List<List<Integer>> ans = pu.permuteUnique(nums);
//        for (List<Integer> list : ans) {
//            for (Integer num : list) {
//                System.out.print(num + " ");
//            }
//            System.out.println();
//        }
//    }

    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        int[] already = new int[nums.length];
        dfs(nums, already);
        return ans;
    }

    private List<List<Integer>> ans = new ArrayList<>();

    private List<Integer> seq = new ArrayList<>();

    private void dfs(int[] nums, int[] already) {
        if (seq.size() == nums.length) {
            List<Integer> tmp = new ArrayList<>(seq);
            ans.add(tmp);
            return;
        }
        List<Integer> indexList = new ArrayList<>();
        for (int i = 0; i < already.length; i++) {
            if (already[i] == 0) {
                indexList.add(i);
            }
        }
        if (!indexList.isEmpty()) {
            for (int i = 0; i < indexList.size(); i++) {
                Integer tmpIndex = indexList.get(i);
                if (i != 0 && nums[indexList.get(i - 1)] == nums[tmpIndex]) {
                    continue;
                }
                seq.add(nums[tmpIndex]);
                already[tmpIndex] = 1;
                dfs(nums, already);
                seq.remove(seq.size() - 1);
                already[tmpIndex] = 0;
            }
        }
    }
}
